package com.huli.utils;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huli.exception.CustomException;
import com.huli.exception.ExceptionEnum;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.LinkedHashMap;
import java.util.List;


@Data
@AllArgsConstructor
@NoArgsConstructor
@Slf4j
public class Result {
    private boolean success;
    private int code;
    private String message;
    private Object data;

    public static <T> T getOriginal(Result result, Class<T> aClass) {
        if (!result.isSuccess()) {
            log.info("|----------> result err message : {}", result.getMessage());
            throw new CustomException(result);
        }

        //JSON.parseObject(JSON.toJSONString(result.getData()), aClass)
        return  new ObjectMapper().convertValue(result.getData(),aClass);
    }

    public static <T> List<T> getOriginalArray(Result result, Class<T> aClass) {
        if (!result.isSuccess()) {
            log.info("|----------> result err message : {}", result.getMessage());
            throw new CustomException(result);
        }
        return JSON.parseArray(JSON.toJSONString(result.getData()),aClass);
    }


    public static Result successResult(Object data) {
        return new Result(true, 200, "success", data);
    }

    public static Result successResult() {
        return successResult(null);
    }

    public static Result failedResult(int code, String message) {
        return new Result(false, code, message, null);
    }

    public static Result failedResult(ExceptionEnum exceptionEnum) {
        return new Result(false, exceptionEnum.getCode(), exceptionEnum.getMessage(), null);
    }

}
